package org.spolo.android.shape;

import java.util.ArrayList;

import org.spolo.android.bean.ActionParameter;
import org.spolo.android.bean.GestureType;
import org.spolo.android.enventmanager.EventHandlerInterface;
import org.spolo.android.nodetree.Vcanvas;
import org.spolo.android.show.Androidshow;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;

public class PicView extends Vcanvas {

	private Bitmap image;
	private Rect dst;
	private float factorX = 1;
	private float factorY = 1;

	private float move_PointY;

	/**
	 * @param bitmap
	 *            用来显示的 一个bitmap对象
	 */
	public PicView(Bitmap bitmap) {
		this.image = bitmap;
		dst = new Rect(0, 0, Androidshow.width, Androidshow.height);
		setDirtyRect(dst.left, dst.top, (image.getWidth()), (image.getHeight()));
		setFactor();
		this.GetEventQueue().addListener(GestureType.onMove_left,
				new MoveControl());
	}

	@Override
	protected void drawSelfImplement(Canvas canvas) {
		// 获取当前图片左上点的Y值
		move_PointY = this.dirty_rect.top;
		canvas.drawBitmap(image, this.startX, this.startY, paint);
	}

	@Override
	protected boolean isChecked(float x, float y) {
		RectF rect = this.getRect();
		if (rect.contains(x, y)) {
			int ix = Math.round((x - dst.left) / factorX);
			int iy = Math.round((y - dst.top) / factorY);
			int clr = image.getPixel(ix, iy);
			if (clr != 0) {
				return true;
			}
		}
		return false;
	}

	private void setFactor() {
		float dest_width = dst.right - dst.left;
		factorX = dest_width / image.getWidth();
		float dest_hight = dst.bottom - dst.top;
		factorY = dest_hight / image.getHeight();
	}

	/**
	 * 图片控制类,用来实现图片在屏幕范围内上下移动的控制
	 * 
	 * @author chenzhongming
	 * @date 2012-5-16
	 */
	class MoveControl implements EventHandlerInterface {
		float lastpointY = 0;
		float firstoneY = 0;

		@Override
		public Object execute(Object parameter) {
			ActionParameter p = (ActionParameter) parameter;
			Vcanvas v = p.getVcanvas();
			ArrayList<MotionEvent> eventlist = p.getEvents();
			// 当手指没有离开屏幕时每次移动都是用最新点减去上一次移动的点,
			// 如果手指离开了屏幕就让上一次的记录点清零,重新记录
			float oneY = eventlist.get(0).getY();
			float twoY = eventlist.get(1).getY();
			float dy = 0;
			if (firstoneY != oneY) {
				lastpointY = 0;
			}
			if (lastpointY != 0) {
				dy = (twoY - lastpointY);
			} else {
				dy = (twoY - oneY);
			}
			lastpointY = twoY;
			//是否移动是看这种图片是否超出了屏幕的范围,如果超出了就不在移动,如果没有超出,就可以继续移动
			//判断的标准就是图片的左上角坐标的的Y值.如果移动的值+Y值,超出了范围就不会再移动
			float target = (dy + move_PointY);
			int limit = (Androidshow.height - image.getHeight());
			if (target >= limit && target <= 0) {
				v.Move(0, dy);
			}
			firstoneY = oneY;
			return null;
		}
	}
}
